document.addEventListener('DOMContentLoaded', function () {
    document.getElementById('cancel-btn').addEventListener('click', function () {
        window.history.back(); // 返回上一个页面
    });

    const getLocationBtn = document.getElementById('get-location-btn');
    getLocationBtn.addEventListener('click', async () => {
        try {
            // 尝试从 localStorage 获取登录时保存的定位信息
            const locationData = localStorage.getItem('location');
            if (locationData) {
                const { province, city } = JSON.parse(locationData);
                const locationInfo = document.getElementById('location-info');
                locationInfo.textContent = `已获取位置：${province} ${city}`;
                locationInfo.classList.replace('text-gray-600', 'text-green-600');
                return;
            }

            // 如果 localStorage 中没有定位信息，使用浏览器定位
            if (!navigator.geolocation) {
                throw new Error('浏览器不支持定位功能');
            }

            // 加载高德定位插件（添加错误处理）
            await new Promise((resolve, reject) => {
                AMap.plugin('AMap.Geolocation', resolve);
                setTimeout(() => reject('高德定位插件加载超时'), 5000); // 5秒加载超时
            });

            const geolocation = new AMap.Geolocation({
                enableHighAccuracy: false, // 关闭高精度模式（优先使用IP定位）
                timeout: 15000, // 延长超时时间到15秒
                buttonOffset: new AMap.Pixel(10, 20),
                zoomToAccuracy: true,
            });

            // 执行定位（使用Promise封装）
            const result = await new Promise((resolve, reject) => {
                geolocation.getCurrentPosition((status, res) => {
                    status === 'complete' ? resolve(res) : reject(res);
                });
            });

            // 成功处理（保持原有逻辑）
            const { latitude, longitude } = result.position;
            const address = result.formattedAddress || '获取到位置坐标';
            const locationInfo = document.getElementById('location-info');

            locationInfo.textContent = `已获取位置：${address}`;
            locationInfo.classList.replace('text-gray-600', 'text-green-600');
            document.getElementById('location-lat').value = latitude;
            document.getElementById('location-lng').value = longitude;
            document.getElementById('location-address').value = address;

        } catch (error) {
            // 细化错误提示（关键优化）
            const locationInfo = document.getElementById('location-info');
            let errorMsg = '定位失败';
            switch (error.message) {
                case 'PERMISSION_DENIED':
                    errorMsg = '请开启位置权限后重试';
                    break;
                case 'POSITION_UNAVAILABLE':
                    errorMsg = '当前位置不可用，请移动到开阔区域';
                    break;
                case 'TIMEOUT':
                    errorMsg = '定位超时，请重试';
                    break;
                default:
                    errorMsg = `定位失败：${error.message || '未知错误'}`;
            }
            locationInfo.textContent = errorMsg;
            locationInfo.classList.replace('text-gray-600', 'text-red-600');
        }
    });

    const postForm = document.getElementById('post-form');
    postForm.addEventListener('submit', async (e) => {
        e.preventDefault();

        const formData = new FormData();
        const title = document.getElementById('post-title').value;
        const content = document.getElementById('post-content').value;
        const tags = document.getElementById('post-tags').value;
        const latitude = document.getElementById('location-lat').value;
        const longitude = document.getElementById('location-lng').value;
        const address = document.getElementById('location-address').value;
        const mediaFiles = document.getElementById('media-upload').files;

        // 封装 postDTO
        const postDTO = {
            post: {
                title: title,
                content: content,
                tags: tags
            },
            postLocation: {
                latitude: latitude,
                longitude: longitude,
                address: address
            }
        };

        // 将 postDTO 转换为 JSON 字符串并添加到 FormData 中
        formData.append('postDTO', JSON.stringify(postDTO));

        for (let i = 0; i < mediaFiles.length; i++) {
            formData.append('files', mediaFiles[i]);
        }

        // 添加用户名（假设用户名存储在 localStorage 中）
        const username = localStorage.getItem('username');
        if (username) {
            formData.append('username', username);
        } else {
            // 处理没有 username 的情况，例如给出提示
            alert('未找到用户名，请重新登录');
            return;
        }

        try {
            const response = await fetch('http://localhost:8081/addPost', {
                method: 'POST',
                body: formData
            });

            if (response.ok) {
                const postSuccess = document.getElementById('post-success');
                postSuccess.classList.remove('hidden');
                postForm.reset();
            } else {
                alert('发帖失败，请重试');
            }
        } catch (error) {
            console.error('请求出错:', error);
            alert('网络错误，请重试');
        }
    });
});